 const state ={
	 cartList:JSON.parse(uni.getStorageSync('cart')||'[]')
 }
const mutations={
	// 将获取的goods数据，保存到state中
	ADDTOCART(state,goods){
	const findRiesult = state.cartList.find((x)=>x.goods_id===goods.goods_id)
	// console.log(findRiesult)
	if(!findRiesult){
		state.cartList.push(goods)
		console.log(state.cartList)
	}else{
		if(findRiesult.goods_count>=findRiesult.goods_number){
			return findRiesult.goods_count=findRiesult.goods_number
		}else{
			findRiesult.goods_count++
		}
		
			
	
	}
	this.commit('SAVETOSTORAGE')
	
},
// 将数据保存到本地
SAVETOSTORAGE(state){
	uni.setStorageSync('cart',JSON.stringify(state.cartList))
},
// 修改购物车中勾选状态
UPGOODSSTATE(state,goods){
	const findResult= state.cartList.find((x)=>x.goods_id===goods.goods_id)
	if(findResult){
		findResult.goods_state=goods.goods_state
		this.commit('SAVETOSTORAGE')
	}
},
// numderbox组件，数量变化
	UPGOODCOUNT(state,goods){
		const findResult = state.cartList.find((x)=>x.goods_id===goods.goods_id)
		if(findResult){
			findResult.goods_count=goods.goods_count
			this.commit('SAVETOSTORAGE')
		}
	},
	//删除购物车的商品
	REMOVEGOODS(state,goods_id){
		state.cartList=state.cartList.filter(x=>x.goods_id!==goods_id)
		this.commit('SAVETOSTORAGE')
		},
		// 点击全选，修改其余勾选框
		UPALLADDRESS(state,newstate){
			state.cartList.forEach(x=>x.goods_state=newstate)
			this.commit('SAVETOSTORAGE')
		}
}
const actions={
	
}
const getters={
	total(state){
		// let c= 0
		// state.cartList.forEach(goods=>c+=goods.goods_count)
		// return c
		return state.cartList.reduce((total,item)=>total+=item.goods_count,0)
	},
	checkedCount(state){
		// 先使用filter，选出选中勾选的商品
		// 在用reduce方法，计算一下选中商品的数量 
		return state.cartList.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
	},
	//计算总价
	checkGoodsmount(state){
		return state.cartList.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
	}
}
export default {
	 state,
	  mutations,
	  actions,
	  getters,
}